package com.sinping.qh.repository.mongo.user.impl;

import com.google.common.collect.Lists;
import com.sinping.qh.domain.common.UnitDomain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.GroupOperation;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhangjin
 * @create 2018/7/2
 */
@Service
public class UserInfoRespositoryImpl {

    @Autowired
    private MongoTemplate template;


    public <T> List<T> getUnitDomain(List<String> groupParams,
                                          Class<?> clazz, Class<T> targetClazz)
    {
        List<AggregationOperation> operations = Lists.newArrayList();

        GroupOperation group = Aggregation.group(groupParams.toArray(new String[groupParams.size()]));

        operations.add(group);

        Aggregation aggregation = Aggregation.newAggregation(operations);
        String table = template.getCollectionName(clazz);
        AggregationResults<T> results = template.aggregate(aggregation, table, targetClazz);
        return results.getMappedResults();
    }

}
